<template>
  <div class="analysis-page">
    <!-- 筛选条件 -->
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="选择班级">
          <el-select
            v-model="filterForm.class"
            placeholder="选择要分析的班级"
            style="width: 200px"
            @change="handleClassChange"
          >
            <el-option label="全部班级" value="" />
            <el-option
              v-for="cls in classes"
              :key="cls"
              :label="cls"
              :value="cls"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="选择课程">
          <el-select
            v-model="filterForm.course"
            placeholder="选择要分析的课程"
            style="width: 200px"
            @change="handleCourseChange"
          >
            <el-option label="平均成绩" value="" />
            <el-option
              v-for="course in courses"
              :key="course"
              :label="course"
              :value="course"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadStatistics">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
          <el-button type="success" @click="generateReport" :loading="generating">
            <el-icon><MagicStick /></el-icon>
            生成AI报告
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="8" :md="6">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="学生总数" :value="statistics.total">
            <template #suffix>人</template>
          </el-statistic>
        </el-card>
      </el-col>

      <el-col :xs="12" :sm="8" :md="6">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="平均分" :value="statistics.average" :precision="2">
            <template #suffix>分</template>
          </el-statistic>
        </el-card>
      </el-col>

      <el-col :xs="12" :sm="8" :md="6">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="最高分" :value="statistics.max">
            <template #suffix>分</template>
          </el-statistic>
        </el-card>
      </el-col>

      <el-col :xs="12" :sm="8" :md="6">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="最低分" :value="statistics.min">
            <template #suffix>分</template>
          </el-statistic>
        </el-card>
      </el-col>

      <el-col :xs="12" :sm="8" :md="6">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="及格率" :value="statistics.passRate" :precision="2">
            <template #suffix>%</template>
          </el-statistic>
        </el-card>
      </el-col>

      <el-col :xs="12" :sm="8" :md="6">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="优秀率" :value="statistics.excellentRate" :precision="2">
            <template #suffix>%</template>
          </el-statistic>
        </el-card>
      </el-col>

      <el-col :xs="12" :sm="8" :md="6">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="良好率" :value="statistics.goodRate" :precision="2">
            <template #suffix>%</template>
          </el-statistic>
        </el-card>
      </el-col>

      <el-col :xs="12" :sm="8" :md="6">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="不及格率" :value="statistics.failRate" :precision="2">
            <template #suffix>%</template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表展示 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :md="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>成绩分布图</span>
            </div>
          </template>
          <div ref="distributionChart" style="height: 350px"></div>
        </el-card>
      </el-col>

      <el-col :xs="24" :md="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>成绩等级占比</span>
            </div>
          </template>
          <div ref="pieChart" style="height: 350px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- AI分析报告 -->
    <el-card shadow="hover" v-if="report" class="report-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><DataAnalysis /></el-icon>
            AI成绩分析报告
          </span>
          <div>
            <el-tag type="success">{{ filterForm.class || '全部班级' }}</el-tag>
            <el-tag type="primary" style="margin-left: 10px">{{ filterForm.course || '平均成绩' }}</el-tag>
          </div>
        </div>
      </template>

      <div class="report-content">
        <el-descriptions title="整体表现评价" :column="1" border>
          <el-descriptions-item>
            <div class="report-section">{{ report.summary }}</div>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="突出问题识别" :column="1" border style="margin-top: 20px">
          <el-descriptions-item>
            <ul class="problem-list">
              <li v-for="(problem, index) in report.problems" :key="index">
                {{ problem }}
              </li>
            </ul>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="教学改进建议" :column="1" border style="margin-top: 20px">
          <el-descriptions-item>
            <ol class="suggestion-list">
              <li v-for="(suggestion, index) in report.suggestions" :key="index">
                {{ suggestion }}
              </li>
            </ol>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="学生分层辅导方案" :column="1" border style="margin-top: 20px">
          <el-descriptions-item label="优秀学生" v-if="report.guidance.excellent">
            {{ report.guidance.excellent }}
          </el-descriptions-item>
          <el-descriptions-item label="良好学生" v-if="report.guidance.good">
            {{ report.guidance.good }}
          </el-descriptions-item>
          <el-descriptions-item label="中等学生" v-if="report.guidance.medium">
            {{ report.guidance.medium }}
          </el-descriptions-item>
          <el-descriptions-item label="及格学生" v-if="report.guidance.pass">
            {{ report.guidance.pass }}
          </el-descriptions-item>
          <el-descriptions-item label="不及格学生" v-if="report.guidance.fail">
            <el-alert type="warning" :closable="false">
              {{ report.guidance.fail }}
            </el-alert>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="总结建议" :column="1" border style="margin-top: 20px">
          <el-descriptions-item>
            <div class="report-section">{{ report.conclusion }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getStatistics, generateAIReport } from '@/api/analysis'
import { getClasses } from '@/api/student'
import axios from 'axios'

const filterForm = reactive({
  class: '',
  course: ''
})

const classes = ref([])
const courses = ref([])
const statistics = ref({
  total: 0,
  average: 0,
  max: 0,
  min: 0,
  passRate: 0,
  excellentRate: 0,
  goodRate: 0,
  failRate: 0,
  distribution: {
    excellent: 0,
    good: 0,
    medium: 0,
    pass: 0,
    fail: 0
  }
})

const report = ref(null)
const generating = ref(false)

const distributionChart = ref()
const pieChart = ref()

let distributionChartInstance = null
let pieChartInstance = null

// 加载班级列表
const loadClasses = async () => {
  try {
    const res = await getClasses()
    classes.value = res.data
  } catch (error) {
    console.error('加载班级列表失败:', error)
  }
}

// 加载课程列表
const loadCourses = async () => {
  try {
    const res = await axios.get('/api/students/filter/courses')
    courses.value = res.data.data
  } catch (error) {
    console.error('加载课程列表失败:', error)
  }
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    const params = {}
    if (filterForm.class) {
      params.class = filterForm.class
    }
    if (filterForm.course) {
      params.course = filterForm.course
    }

    const res = await getStatistics(params)
    statistics.value = res.data

    // 更新图表
    await nextTick()
    renderCharts()
  } catch (error) {
    ElMessage.error('加载统计数据失败')
  }
}

// 渲染图表
const renderCharts = () => {
  renderDistributionChart()
  renderPieChart()
}

// 渲染成绩分布柱状图
const renderDistributionChart = () => {
  if (!distributionChart.value) return

  if (!distributionChartInstance) {
    distributionChartInstance = echarts.init(distributionChart.value)
  }

  const option = {
    title: {
      text: '各等级人数分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: ['优秀\n(90-100)', '良好\n(80-89)', '中等\n(70-79)', '及格\n(60-69)', '不及格\n(<60)']
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      {
        data: [
          { value: statistics.value.distribution.excellent, itemStyle: { color: '#67C23A' } },
          { value: statistics.value.distribution.good, itemStyle: { color: '#409EFF' } },
          { value: statistics.value.distribution.medium, itemStyle: { color: '#E6A23C' } },
          { value: statistics.value.distribution.pass, itemStyle: { color: '#F56C6C' } },
          { value: statistics.value.distribution.fail, itemStyle: { color: '#909399' } }
        ],
        type: 'bar',
        barWidth: '60%'
      }
    ]
  }

  distributionChartInstance.setOption(option)
}

// 渲染饼图
const renderPieChart = () => {
  if (!pieChart.value) return

  if (!pieChartInstance) {
    pieChartInstance = echarts.init(pieChart.value)
  }

  const option = {
    title: {
      text: '成绩等级占比',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    series: [
      {
        name: '成绩等级',
        type: 'pie',
        radius: '65%',
        center: ['60%', '50%'],
        data: [
          { value: statistics.value.distribution.excellent, name: '优秀', itemStyle: { color: '#67C23A' } },
          { value: statistics.value.distribution.good, name: '良好', itemStyle: { color: '#409EFF' } },
          { value: statistics.value.distribution.medium, name: '中等', itemStyle: { color: '#E6A23C' } },
          { value: statistics.value.distribution.pass, name: '及格', itemStyle: { color: '#F56C6C' } },
          { value: statistics.value.distribution.fail, name: '不及格', itemStyle: { color: '#909399' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  pieChartInstance.setOption(option)
}

// 课程改变
const handleCourseChange = () => {
  loadStatistics()
  report.value = null // 清空报告
}

// 班级改变
const handleClassChange = () => {
  loadStatistics()
  report.value = null // 清空报告
}

// 生成AI报告
const generateReport = async () => {
  if (statistics.value.total === 0) {
    ElMessage.warning('暂无数据，无法生成报告')
    return
  }

  generating.value = true
  try {
    const data = {
      class: filterForm.class || '全部班级',
      course: filterForm.course || '',
      scope: filterForm.class ? 'class' : 'all'
    }

    const res = await generateAIReport(data)
    report.value = res.data.report
    ElMessage.success('AI报告生成成功')
  } catch (error) {
    ElMessage.error('生成AI报告失败')
  } finally {
    generating.value = false
  }
}

// 监听窗口大小变化
const handleResize = () => {
  distributionChartInstance?.resize()
  pieChartInstance?.resize()
}

onMounted(() => {
  loadClasses()
  loadCourses()
  loadStatistics()
  window.addEventListener('resize', handleResize)
})
</script>

<style scoped>
.analysis-page {
  max-width: 1400px;
  margin: 0 auto;
}

.filter-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.charts-row {
  margin-bottom: 20px;
}

.report-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.report-content {
  padding: 10px 0;
}

.report-section {
  line-height: 1.8;
  font-size: 15px;
  color: #303133;
}

.problem-list {
  margin: 0;
  padding-left: 20px;
  line-height: 2;
  color: #F56C6C;
}

.suggestion-list {
  margin: 0;
  padding-left: 20px;
  line-height: 2;
  color: #409EFF;
}

.problem-list li,
.suggestion-list li {
  margin: 8px 0;
}
</style>
